<template>
  <div class="entry-detail">
    <!-- 头部信息 -->
    <el-card class="header-card">
      <h1>{{ entry.title }}</h1>
      <div class="meta">
        <el-tag type="info">👁️ {{ entry.view_count }}</el-tag>
        <el-tag type="warning">⭐ {{ entry.favorite_count }}</el-tag>
        <span class="author">作者：{{ entry.creator_name }}</span>
        <span class="time">创建于 {{ formatTime(entry.created_at) }}</span>
      </div>
    </el-card>

    <!-- 内容区域 -->
    <el-card class="content-card">
      
      <div class="content" v-html="entry.content"></div>
      <!-- 操作栏 -->
      <div class="action-bar">
        <el-button v-if="canEdit" type="warning" @click="showUploadDialog">
          上传附件
        </el-button>
        <el-button v-if="canEdit" type="primary" @click="handleEdit">
          编辑词条
        </el-button>
        <el-button v-if="canDelete" type="danger" @click="handleDelete">
          删除词条
        </el-button>
        <el-button :type="isFavorite ? 'success' : 'primary'" @click="toggleFavorite">
          {{ isFavorite ? '已收藏' : '收藏' }}
        </el-button>
      </div>
      <!-- 附件列表 -->
      <div v-if="entry.attachments.length" class="attachments">
        <h3>相关附件</h3>
        <el-table :data="entry.attachments">
          <el-table-column prop="title" label="文件名" />
          <el-table-column label="类型" width="120">
            <template #default="{ row }">
              <el-tag>{{ row.attachment_type }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="上传时间">
            <template #default="{ row }">
              {{ formatTime(row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="downloadAttachment(row.file_path)">
                下载
              </el-button>
              <el-button v-if="canEdit" type="danger" size="small" @click="deleteAttachment(row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 相关词条 -->
    <el-card class="related-entries" v-if="relatedEntries.length > 0">
      <h3>相关词条</h3>
      <div class="entry-list">
        <el-card v-for="entry in relatedEntries" :key="entry.related_entry" class="related-entry" @click="navigateToRelated(entry.related_entry)">
          <h4 class="title">{{ entry.related_entry_title }}</h4>
          <p class="summary">{{ entry.related_entry_summary }}</p>
          <!-- <div class="meta">
            <el-tag type="info" size="small">👁️ {{ entry.view_count }}</el-tag>
            <el-tag type="warning" size="small">⭐ {{ entry.favorite_count }}</el-tag>
          </div> -->
        </el-card>
      </div>
    </el-card>
    <!-- 编辑词条对话框 -->
    <el-dialog :title="editForm.id ? '编辑词条' : '新建词条'" v-model="editDialogVisible" width="800px">
      <el-form :model="editForm" :rules="editRules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="editForm.title" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select v-model="editForm.category" placeholder="选择分类" clearable>
            <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input v-model="editForm.tags" placeholder="多个标签用逗号分隔" />
        </el-form-item>
        <el-form-item label="摘要" prop="summary">
          <el-input v-model="editForm.summary" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input v-model="editForm.content" type="textarea" :rows="8" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEntry">保存</el-button>
      </template>
    </el-dialog>
    <el-dialog title="上传附件" v-model="uploadDialogVisible">
      <el-form :model="uploadForm" label-width="100px">
        <el-form-item label="附件标题" prop="title">
          <el-input v-model="uploadForm.title" placeholder="请输入附件标题" />
        </el-form-item>
        <el-form-item label="附件类型">
          <el-select v-model="uploadForm.attachment_type">
            <el-option label="文档" value="document" />
            <el-option label="图片" value="image" />
            <el-option label="视频" value="video" />
            <el-option label="音频" value="audio" />
          </el-select>
        </el-form-item>
        <el-form-item label="文件">
          <el-upload ref="uploadRef" :before-upload="beforeUpload" :limit="1" action="/api/hzadmin/public/upload_image/"
            :on-success="handleFileSuccess">
            <el-button type="primary">选择文件</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持扩展名：.jpg, .jpeg, .png, .doc, .docx, .mp3, mp4, .pptx, .pdf<br />大小不超过50MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="uploadDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitUpload">确认上传</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import {
  entry_get,
  getFavoriteEntries,
  entry_delete,
  createFavorite,
  deleteFavorite,
  getRelatedEntries,
  entry_update,
  category_list,
  uploadAttachment,
  deleteAttachment as deleteAttachmentApi,
  getEntryAttachments,
  entries_view_count
} from '/@/api/encyclopedia'
import { useUserConfig } from '/@/stores/UserInfoConfig'

const { userInfo } = useUserConfig()

const route = useRoute()
const router = useRouter()
const isComponentActive = ref(true)

// 新增附件上传相关状态
const uploadDialogVisible = ref(false)
const uploadForm = reactive({
  title: '',
  file: null,
  attachment_type: 'document'
})
const uploadRef = ref(null)

// 新增编辑相关状态
const editDialogVisible = ref(false)
const editForm = reactive({
  id: null,
  title: '',
  category: null,
  tags: '',
  summary: '',
  content: ''
})

// 新增分类选项
const categoryOptions = ref([])

// 词条基础数据
const entry = ref({
  title: '',
  content: '',
  view_count: 0,
  favorite_count: 0,
  creator: null,
  created_at: '',
  attachments: []
})

// 相关词条数据
const relatedEntries = ref([])

// 收藏状态
const isFavorite = ref(false)
const favorite_id = ref(null)

// 获取词条详情
const fetchEntry = async () => {
  try {
    const res = await entry_get(route.params.id)
    entry.value = res.data
  } catch (error) {
    // ElMessage.error('获取词条详情失败')
  }
}


// 新增获取相关词条方法
const fetchRelatedEntries = async () => {
  try {
    const res = await getRelatedEntries(route.params.id)
    relatedEntries.value = res.data
  } catch (error) {
    ElMessage.error('相关词条加载失败')
  }
}

// 权限判断
const canEdit = computed(() => {
  // 根据实际用户状态判断
  return entry.value.creator === userInfo.id || userInfo.isAdmin
})

const canDelete = computed(() => {
  return canEdit.value
})

// 时间格式化
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

const navigateToRelated = (id) => {
  isComponentActive.value = true
  router.replace(`/entry/${id}`)
}

const fetchFavorites = async () => {
  try {
    const res = await getFavoriteEntries({ entry_id: route.params.id, user_id: userInfo.id, page_size: 9999999999999, page: 1 })
    if (res.code !== 200) {
      ElMessage.error('获取收藏状态失败')
      return;
    }
    res.data.favorites.forEach((favorite) => {
      if (favorite.entry == route.params.id) {
        isFavorite.value = true;
        favorite_id.value = favorite.id;
        return;
      }
    })
  } catch (error) {
    ElMessage.error('获取收藏状态失败')
  }
}

// 删除词条
const handleDelete = async () => {
  try {
    await ElMessageBox.confirm('确定要删除该词条吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await entry_delete(route.params.id)
    ElMessage.success('删除成功')
    router.push('/encyclopedia')
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 收藏操作
const toggleFavorite = async () => {
  try {
    if (isFavorite.value) {
      await deleteFavorite(favorite_id.value)
      entry.value.favorite_count--
    } else {
      await createFavorite({ entry: entry.value.id, user: userInfo.id })
      entry.value.favorite_count++
    }
    fetchFavorites()
    isFavorite.value = !isFavorite.value
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 新增分类加载方法
const loadCategories = async () => {
  try {
    const res = await category_list({ page_size: 1000 })
    categoryOptions.value = flattenCategories(res.data.categories)
  } catch (error) {
    // ElMessage.error('分类加载失败')
  }
}

// 分类扁平化处理
const flattenCategories = (categories) => {
  return categories.reduce((acc, curr) => {
    acc.push({ id: curr.id, name: curr.name })
    if (curr.children) {
      acc.push(...flattenCategories(curr.children))
    }
    return acc
  }, [])
}

// 新增表单验证规则（与EncyclopediaManage一致）
const editRules = reactive({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  category: [{ required: true, message: '请选择分类', trigger: 'change' }],
  summary: [{ required: true, message: '请输入摘要', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
})

// 修改handleEdit方法
const handleEdit = () => {
  Object.assign(editForm, {
    id: entry.value.id,
    title: entry.value.title,
    category: entry.value.category,
    tags: entry.value.tags,
    summary: entry.value.summary,
    content: entry.value.content
  })
  editDialogVisible.value = true
}

// 新增保存方法
const saveEntry = async () => {
  try {
    const payload = {
      ...editForm,
      creator: entry.value.creator,
    }

    await entry_update(entry.value.id, payload)
    ElMessage.success('保存成功')
    editDialogVisible.value = false
    await fetchEntry() // 刷新数据
  } catch (error) {
    ElMessage.error(error.message)
  }
}

// 文件类型验证
const beforeUpload = (file) => {
  const validExtensions = [
    '.jpg', '.jpeg', '.png',
    '.doc', '.docx',
    '.mp3', '.mp4',
    '.pptx', '.pdf'
  ]
  const fileExtension = file.name.slice(file.name.lastIndexOf('.')).toLowerCase()
  const isValid = validExtensions.includes(fileExtension)
  const isLt50M = file.size / 1024 / 1024 < 50

  if (!isValid) {
    ElMessage.error('不支持的文件格式')
    return false
  }
  if (!isLt50M) {
    ElMessage.error('文件大小不能超过50MB')
    return false
  }
  return true
}

// 文件选择处理
const handleFileSuccess = async (res) => {
  if (res.code !== 200) {
    ElMessage.error('文件上传失败')
    return
  }
  uploadForm.file = res.data
}

// 显示上传对话框
const showUploadDialog = () => {
  uploadDialogVisible.value = true
  uploadForm.file = null
  uploadForm.title = ''
  uploadForm.attachment_type = 'document'
  nextTick(() => {
    uploadRef.value?.clearFiles()
  })
}

// 提交上传
const submitUpload = async () => {
  if (!uploadForm.title.trim()) {
    ElMessage.warning('请输入附件标题')
    return
  }

  if (!uploadForm.file) {
    ElMessage.warning('请选择要上传的文件')
    return
  }

  try {
    const payload = {
      title: uploadForm.title,
      file_path: uploadForm.file,
      attachment_type: uploadForm.attachment_type,
      entry: entry.value.id
    }
    const res = await uploadAttachment(payload)
    if (res.code !== 200) {
      ElMessage.error('上传失败')
      return
    }
    entry.value.attachments.push(res.data)

    ElMessage.success('上传成功')
    uploadDialogVisible.value = false

  } catch (error) {
    ElMessage.error('上传失败')
  }
}

const downloadAttachment = (filePath) => {
  const link = document.createElement('a')
  const url = filePath.startsWith('http') ? filePath : '/api/' + filePath
    link.href = url;
    link.download = url.split('/').pop()
    link.style.display = 'none'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
}

const getAttachments = async () => {
  try {
    const res = await getEntryAttachments({ entry_id: entry.value.id, page_size: 9999999999999, page: 1})
    entry.value.attachments = res.data
  } catch (error) {
    ElMessage.error('获取附件失败')
  }
}

// 删除附件
const deleteAttachment = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该附件？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const res = await deleteAttachmentApi(id)
    if (res.code!== 200) {
      ElMessage.error('删除失败')
      return 
    }
    entry.value.attachments = entry.value.attachments.filter(a => a.id!== id)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const incrementViewCount = async () => {
  try {
    await entries_view_count(route.params.id)
  } catch (error) {
    console.error('浏览量统计失败:', error)
  }
}

const init = async () => {
  await fetchEntry()
  await fetchFavorites()
  await fetchRelatedEntries()
  await loadCategories()
  await getAttachments()
  incrementViewCount()
}

// 添加路由守卫
router.beforeEach((to, from) => {
  // 当从词条详情页跳转到非词条详情页时，标记组件为非激活状态
  if (from.name === 'EntryDetail' && to.name !== 'EntryDetail') {
    isComponentActive.value = false
  }
})

// 初始化加载
watch(
  () => route.params.id,  // 监听路由ID参数
  (newId) => {            // 变化时执行回调
    if (newId && isComponentActive.value) {
      init()              // 重新初始化数据
    }
  },
  { immediate: true }     // 组件挂载时立即执行
)

// 添加组件卸载逻辑
onUnmounted(() => {
  isComponentActive.value = false
})
</script>

<style scoped>
.entry-detail {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.header-card {
  margin-bottom: 20px;

  h1 {
    margin: 0 0 15px 0;
    color: var(--el-color-primary);
  }

  .meta {
    display: flex;
    align-items: center;
    gap: 15px;

    .el-tag {
      margin-right: 10px;
    }
  }
}

.entry-list {
  margin-top: 20px;
  .el-card {
    margin-bottom: 20px;
    transition: transform 0.2s;
    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 2px 12px rgba(0,0,0,0.1);
    }
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.content-card {
  margin-bottom: 30px;

  .content {
    line-height: 1.8;
    font-size: 16px;
    margin-bottom: 30px;
  }
}

.action-bar {
  margin-top: 20px;
  display: flex;
  gap: 15px;
  justify-content: center;
}

.attachments {
  margin-top: 30px;

  h3 {
    color: var(--el-text-color-regular);
    margin-bottom: 15px;
  }
}

.el-upload__tip {
  color: var(--el-text-color-secondary);
  font-size: 12px;
  margin-top: 7px;
}
</style>
